﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.Objects;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Data.Entity;

namespace RepoInfrastructure
{
	public class ContextRepository<T, TContext> : ContextReadonlyRepository<T, TContext>,  IRepository<T> 
		where T : class
        where TContext : DbContext 
	{
        public ContextRepository(): base() {}
        public ContextRepository(DbContext db) : base(db) { }

        public virtual T Create(T TObject)
        {
            var newEntry = DbSet.Add(TObject);
            //if (!shareContext)
                Context.SaveChanges();
            return newEntry;
        }

        public virtual int Update(T TObject)
        {
            var entry = Context.Entry(TObject);
            DbSet.Attach(TObject);
            entry.State = EntityState.Modified;
            //if (!shareContext)
                return Context.SaveChanges();
            //return 0;
        }

        public virtual int Delete(T TObject)
        {
            DbSet.Remove(TObject);
            //if (!shareContext)
            return Context.SaveChanges();
            //return 0;
        }

        public virtual int Delete(Expression<Func<T, bool>> predicate)
        {
            var objects = Filter(predicate);
            foreach (var obj in objects)
                DbSet.Remove(obj);
            //if (!shareContext)
                return Context.SaveChanges();
            //return 0;
        }
    }
}
